from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.urls import reverse
from django.views.generic import View
from user.models import User, Address
from goods.models import GoodsSKU
from django.contrib.auth import authenticate, login, logout
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
from django.conf import settings
from celery_tasks.tasks import send_register_active_email
import re
from utils.mixin import LoginRequiredMixin
from django_redis import get_redis_connection
from order.models import OrderGoods, OrderInfo
from django.core.paginator import Paginator
# Create your views here.

class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        username = request.POST.get('user_name')
        password = request.POST.get('pwd')
        email = request.POST.get('email')
        allow = request.POST.get('allow')

        if not all([username, password, email]):
            return render(request, 'register.html', {'errmsg': '数据不完整'})

        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return render(request, 'register.html', {'errmsg': '邮箱不正确'})
        if allow != 'on':
            return render(request, 'register.html', {'errmsg': '请同意协议'})
        # 验证用户名是否有重复
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = None

        if user:
            return render(request, 'register.html', {'errmsg': '用户名已存在'})

        user = User.objects.create_user(username, email, password)
        user.is_active = 0
        user.save()

        serializer = Serializer(settings.SECRET_KEY, 3600)
        info = {"confirm": user.id}
        token = serializer.dumps(info)
        token = token.decode()
        # 发邮件
       # send_register_active_email.delay(email, username, token)
        send_register_active_email(email, username, token)
        # 返回应答, 跳转到首页
        return redirect(reverse('goods:index'))


class ActiveView(View):
    '''用户激活'''
    def get(self, request, token):

        serializer = Serializer(settings.SECRET_KEY, 3600)
        try:
            # 解密token
           info = serializer.loads(token)
           user_id = info['confirm']
           user = User.objects.get(id=user_id)
           user.is_active = 1
           user.save()

           return redirect(reverse("user:login"))

        except SignatureExpired as e:
           # 激活链接已过期
            return HttpResponse('激活链接已过期')

class LoginView(View):
    ''' 登录视图类 '''
    def get(self, request):
        if 'username' in request.COOKIES:
            username = request.COOKIES.get('username')
            checked = "checked"
        else:
            username = ''
            checked = ''
        return render(request, 'login.html', {"username": username, "checked": checked})

    def post(self, request):
        username = request.POST.get("username")
        password = request.POST.get("pwd")

        if not all([username, password]):
            return render(request, 'login.html', {"errmsg":'帐号和密码都不能为空'})

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                # 用户已激活
                # 记录用户的登录状态
                login(request, user)
                # 获取登录后所要跳转到的地址
                # 默认跳转到首页
                next_url = request.GET.get('next', reverse('goods:index'))
                # 跳转到next_url
                response = redirect(next_url)
                # 判断是否需要记住用户名
                remeber = request.POST.get("remeber")
                if remeber == 'on':
                    response.set_cookie("username", username, max_age=7*24*3600)
                else:
                    response.delete_cookie("username")
                return response
            else:
                return render(request, 'login.html', {"errmsg": '用户未激活'})
        else:
            return render(request, 'login.html', {"errmsg": '帐号或密码错误'})

class LogoutView(View):
    '''退出登录'''
    def get(self, request):
        '''退出登录'''
        # 清除用户的session信息
        logout(request)
        return redirect(reverse("goods:index"))


class UserInfoView(LoginRequiredMixin, View):
    '''用户中心-个人信息'''
    def get(self, request):
        #获取用户基本信息
        user =request.user
        address = Address.objects.get_default_address(user)
        print('address:%s' % str(address))
        # 获取浏览的历史记录
        con = get_redis_connection('default')
        history_key = 'history_%d' % user.id
        sku_ids = con.lrange(history_key, 0, 4)
        # 遍历获取用户浏览的商品信息
        goods_li = []
        for id in sku_ids:
            goods = GoodsSKU.objects.get(id=id)
            goods_li.append(goods)
            # 组织上下文
        context = {'page': 'user',
                   'address': address,
                   'goods_li': goods_li}
        return render(request, "user_center_info.html", context)


class UserOrderView(LoginRequiredMixin, View):
    '''用户中心-全部订单'''
    def get(self, request, page_no=1):
        user = request.user
        orderInfos = OrderInfo.objects.filter(is_delete=False, user=user).order_by("-create_time")

        for orderInfo in orderInfos:
            orderGoods = OrderGoods.objects.filter(is_delete=False, order=orderInfo)
            for orderGood in orderGoods:
                orderGood.amount = orderGood.count*orderGood.price

            orderInfo.goods = orderGoods
            order_status = orderInfo.order_status
            orderInfo.order_status_name = OrderInfo.ORDER_STATUS[order_status]
            orderInfo.pay_method_name = OrderInfo.PAY_METHODS[str(orderInfo.pay_method)]

        pageinator = Paginator(orderInfos, 2)

        try:
            page_no = int(page_no)
        except Exception:
            page_no = 1

        if page_no > pageinator.num_pages:
            page_no = 1

        order_page = pageinator.page(page_no)

        # 获取5页页码
        if pageinator.num_pages <= 5:
            page_nums = range(1, pageinator.num_pages + 1)
        elif page_no <= 3:
            page_nums = range(1, 6)
        elif page_no >= pageinator.num_pages - 2:
            page_nums = range(pageinator.num_pages - 4, pageinator.num_pages + 1)
        else:
            page_nums = range(page_no - 2, page_no + 3)

        context = {
            "page": "order",
            "order_page": order_page,
            "page_nums": page_nums
        }

        return render(request, "user_center_order.html", context)

class UserAddressView(LoginRequiredMixin, View):
    ''' 用户中心-收货地址 '''
    def get(self, request):
        user = request.user
        address = Address.objects.get_default_address(user)

        return render(request, "user_center_site.html", {"page": "address", "address": address})

    def post(self, request):
        receiver = request.POST.get('receiver')
        addr = request.POST.get('addr')
        zip_code = request.POST.get('zip_code')
        phone = request.POST.get('phone')

        if not all([receiver, addr, phone]):
            return render(request, 'user_center_site.html', {"page": "address", 'errmsg': '数据不完整'})

            # 校验手机号
        if not re.match(r'^1[3|4|5|7|8][0-9]{9}$', phone):
            return render(request, 'user_center_site.html', {"page": "address", 'errmsg': '手机格式不正确'})
        user = request.user
        address = Address.objects.get_default_address(user)
        if address:
            is_default = False
        else:
            is_default = True

            # 添加地址
            Address.objects.create(user=user,
                                   receiver=receiver,
                                   addr=addr,
                                   zip_code=zip_code,
                                   phone=phone,
                                   is_default=is_default)

            # 返回应答,刷新地址页面
            return redirect(reverse('user:address'))  # get请求方式